package org.example.netty.http;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.AttributeKey;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * http协议工具类
 */
public class HttpProtocolHelper {

    /**
     * httpversion版本
     */
    public static AttributeKey<HttpVersion> HTTPVERSION_KEY = AttributeKey.valueOf("HTTPVERSION");

    /**
     * 是否是keep_alive
     */
    public static AttributeKey<Boolean> KEEP_ALIVE_KEY = AttributeKey.valueOf("KEEP_ALIVE_KEY");

    /**
     * 解析uri地址
     */
    public static Map<String, Object> parseFromUri(String uri) {
        Map<String, Object> map = new HashMap<>();

        try {
            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri);
            Map<String, List<String>> parameters = queryStringDecoder.parameters();
            for (Map.Entry<String, List<String>> parameterItem : parameters.entrySet()) {
                // 暂时只取第一个值
                map.put(parameterItem.getKey(), parameterItem.getValue().get(0));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return map;
    }

    public static void sendJsonContent(String json, ChannelHandlerContext ctx) {
        HttpVersion httpVersion = ctx.channel().attr(HTTPVERSION_KEY).get();

        FullHttpResponse response = new DefaultFullHttpResponse(httpVersion, HttpResponseStatus.OK);
        response.headers().add("Content-Type", "application/json;charset=UTF-8");

        // body内容
        byte[] contents = json.getBytes(StandardCharsets.UTF_8);
        response.headers().add("Content-Length", contents.length);
        response.content().writeBytes(Unpooled.wrappedBuffer(contents));

        ctx.writeAndFlush(response);
    }

    /**
     * http协议是否是1.0
     * @return
     */
    public static boolean isHttp10(ChannelHandlerContext ctx) {
        HttpVersion httpVersion = ctx.channel().attr(HTTPVERSION_KEY).get();
        return httpVersion.text().endsWith("HTTP/1.0");
    }

    public static boolean isHttp11(ChannelHandlerContext ctx) {
        HttpVersion httpVersion = ctx.channel().attr(HTTPVERSION_KEY).get();
        return httpVersion.text().endsWith("HTTP/1.1");
    }

    /**
     * 判断是否keep-alive
     * @param ctx
     * @return
     */
    public static boolean isKeepAlive(ChannelHandlerContext ctx) {
        return ctx.channel().attr(KEEP_ALIVE_KEY).get();
    }
}
